package com.pzhu.gmall.user.service.impl;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.pzhu.gmall.bean.UmsMemberReceiveAddress;
import com.pzhu.gmall.bean.UserMember;
import com.pzhu.gmall.service.UserService;
import com.pzhu.gmall.user.mapper.UmsMemberReceiveAddressMapper;
import com.pzhu.gmall.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import tk.mybatis.mapper.entity.Example;

/**
 * @author 刘鹏 liupeng
 * @date 2019/10/21
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UmsMemberReceiveAddressMapper umsMemberReceiveAddressMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<UserMember> getAllUser() {
        return userMapper.selectAll();
    }

    @Override
    public List<UmsMemberReceiveAddress> getAddressesByUserId(String id) {
        Example e = new Example(UmsMemberReceiveAddress.class);
        e.createCriteria().andEqualTo("memberId", id);
//        umsMemberReceiveAddressMapper.select(); 直接对象
        return umsMemberReceiveAddressMapper.selectByExample(e);
    }

    @Override
    public UserMember login(UserMember userMember) {
        //使用缓存
        String userStr = stringRedisTemplate.opsForValue().get(userMember.getUsername() + userMember.getPassword());
        if (StringUtils.isNotBlank(userStr)) {
            UserMember userMemberCache = JSON.parseObject(userStr, UserMember.class);
            return userMemberCache;
        }
        //缓存中没有
        UserMember userMemberFromDb = userMapper.selectOne(userMember);
        stringRedisTemplate.opsForValue().set(userMember.getUsername() + userMember.getPassword(), JSON.toJSONString(userMemberFromDb), 60 * 60 * 2L);
        return userMember;
    }
}
